<template>
  <div class="vedio_module">
    <div class="upload_moudle" v-if="isEdit">
     <div v-show="haveOneUrl">
       <uploadFile ref="uploadFileRef" v-bind="uploadProps" :refnameBase="refname" @changeFile="changeFile" @closeLoading="closeLoading" v-model="changeFileArr"></uploadFile>
      <div class="require_tip">
          {{tipMsgRequire}}
      </div>
     </div>
    </div>
    <!-- 多选  -->
    <div v-if="multiple">
      <el-scrollbar :height="`calc(100vh - ${maxHei}px)`">
        <div class="vedio_mulit">
          <div v-for="(vedioItem, vindex) in uploadSuccessData" :key="vindex" class="vedio_item">
            <video
              :ref="el => handleSetInputMap(el, vindex)"
              :src="vedioItem?.file_url"
              @ended="onVideoEnded('mulit', vindex, vedioItem)"
              controlslist="nodownload nofullscreen noremoteplayback"
              :controls="vedioItem?.isPlay"
              style="width: 100%; height: 100%"
            ></video>
            <div class="closePlay" v-show="vedioItem?.isPlay" @click="onVideoEnded('mulit', vindex, vedioItem)">
              <!-- <el-icon><Close /></el-icon> -->
              关闭
            </div>
            <div class="shadowVedio" v-show="!vedioItem?.isPlay">
              <div title="播放">
                <span class="successTip" @click="playVedioFun('mulit', vindex, vedioItem)">
                  <el-icon><CaretRight /></el-icon>
                </span>
              </div>
            </div>
            <div class="footerTip" v-show="!vedioItem?.isPlay">
              <div class="mulitName">{{ vedioItem.name }}</div>
              <div class="del_icon" title="删除" @click="delVedio('mulit', vindex, vedioItem)">
                <el-icon><Delete /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 单选 -->
    <div class="vedio_show" :class="uploadClass" v-else>
     
      <div class="vedio_item" v-if="vedioUrl">
        <video
          ref="videoElement"
          :src="vedioUrl"
          @ended="onVideoEnded"
          controlslist="nodownload nofullscreen noremoteplayback"
          :controls="!playShow"
          style="width: 100%; height: 100%"
        ></video>
        <div class="closePlay" v-show="!playShow" @click="onVideoEnded">
          {{$t('goods_batchUploads_productMainImage.close_tip')}}
        </div>

        <div class="shadowVedio" v-show="playShow">
          <div :title="$t('goods_batchUploads_productMainImage.play')">
            <span class="successTip" v-show="fileObj?.status == 'success'" @click="playVedioFun">
              <el-icon><CaretRight /></el-icon>
            </span>
            <div class="errTip" v-show="fileObj?.raw?.tip">
              <el-tooltip class="box-item" effect="dark" :content="fileObj?.raw?.tip" placement="top">
                <span>
                  <el-icon><WarningFilled /></el-icon
                ></span>
              </el-tooltip>
            </div>
          </div>
          <div class="del_icon" :title="$t('merak.delete')" @click="delVedio" v-if="isEdit">
           <el-icon><Delete /></el-icon>
          </div>
        </div>
      </div>

      
       <div class="empty"  v-if="!initData&&!vedioUrl&&isEmpty" >
        <div >
          <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import EmptyPng from "@/assets/images/empty.png";
import { Path } from "@/api/modules/upload.ts";
import { reactive, ref, onMounted, nextTick, computed, watch } from "vue";
// Path.batchImgSpuss
import { ElMessage } from "element-plus";
import layoutContent from "@/components/LayoutComponents/index.vue";
import uploadFile from "@/components/uploadFileMerak/index.vue";
import { delImagesApi } from "@/api/modules/goodsArchive/batchupload/goodsImmage";

import { successMsg, failMsg, confirmWarningMsg } from "@/utils/messageUtils";
import { ResultEnum } from "@/enums/httpEnum";
 import defaultImg from "@/assets/images/goods_img.webp";
const defaultVedio = defineModel<Record<string, any>>({ default: {} }); //默认值
const props = withDefaults(
  defineProps<{
     isEmpty?:boolean,//是否为空
    initData?:boolean,//初始化加载
   refname?:object;//上一个页面的refName，搭配loading使用
    occupyHei?: number;
    path: string;
    isEdit?: boolean; //是否编辑
    params?: object;
    multiple?: boolean; //是否多选
    tipMsg?:string;
    accept?:string;
    listType?:string;
    uploadClass?:string;
    tipMsgRequire?:string;//当前页面提示
    toastBool?:boolean;
  }>(),
  {
    listType:'picture-card',//默认央视
    uploadClass:'drag_upload_picture',//默认class
    tipMsgRequire:"",
    tipMsg:"，支持mp4格式",
    occupyHei: 0,
    path: "",
    isEdit: true,
   isEmpty:true,
    accept: ".mp4"
  }
);
const haveOneUrl=ref(true);//picUpload  针对 class为"picUpload" 如果有数据不显示，默认都显示
const uploadProps = reactive({
  uploadLoading: true, //外部上传loading
  multiple: props.multiple,
  listType: props.listType,
  uploadClass:props.uploadClass,
  path: props.path,
  fileListShow: false,
  accept: props.accept, //只允许shipin上传
  tipShow: false,
  tipMsgOther:props.tipMsg, 
  maxSize: 200,
  params: props.params,
  toastBool:props.toastBool
});

const uploadFileRef=ref(null);

// occupyHei

const maxHei = computed(() => {
  let uploadHei = 230;
  let otherHei = 220;
  let alHei = otherHei + props.occupyHei;
  if (props.isEdit) {
    alHei = uploadHei + otherHei + props.occupyHei;
  }

  // console.log(alHei, "所有高度");
  return alHei;
});

//#region 单个视频上传
let changeFileArr = ref([]); //初始化默认数据
let fileObj = ref({});
let vedioUrl = computed(() => {
  let url = "";
  let len = changeFileArr.value.length;
  if (len == 0) {
    fileObj.value = {
      response: defaultVedio.value,
      status: "success"
    };
  }

  if (len == 1 && !Object.keys(defaultVedio.value).length) {
    fileObj.value = changeFileArr.value[0];
  }

  if (fileObj.value?.status == "success") {
    url = fileObj.value?.response?.file_url;
  } else {
    if (fileObj.value?.raw?.tip) {
      url = fileObj.value?.url;
    }
  }
  // console.log(url);
  return url;
});
//#endregion

//#region 多个视频上传
const inputRefMap = ref({});
const handleSetInputMap = (el: refItem, num: number) => {
  if (el) {
    inputRefMap.value[`videoRef_${num}`] = el;
  }
};

const uploadVedioMulitData = ref([]);
const uploadSuccessDataCom = computed(() => {
  let newArr = [],
    fileObj = {};
  uploadVedioMulitData.value.map(cItem => {
    if (cItem?.response) {
      cItem.response.isPlay = false;
      fileObj[cItem?.response?.id] = cItem?.response;
    }
  });

  return Object.values(fileObj);
});

const uploadSuccessData = ref([]);
watch(
  () => uploadSuccessDataCom.value,
  (newVal, oldVal) => {
    uploadSuccessData.value = newVal;
  }
);
// isPlay
//#endregion
//关闭loading
const closeLoading=()=>{
    if(props.uploadClass=="picUpload"){
        //上传之后不显示上传控件
        haveOneUrl.value=false;
      }
}
const changeFile = filelist => {
  {
    if (props.multiple) {
      //多选
      // console.log(filelist, "视频文件。。。");

      let otherFile = [];
      if (filelist.length) {
        filelist.map(fItem => {
          let type = uploadFileRef.value.getJudgeFileType(fItem);
          if (type == "zip") {
            //压缩包处理
            console.log(fItem);
            let successData = fItem.response?.success,
              failData = fItem.response?.fail;
            if (successData && successData.length) {
              successData.map(sItem => {
                otherFile.push({
                  percentage: 100,
                  status: "success",
                  response: sItem
                });
              });
            }

            if (failData && failData.length) {
              failData.map(errItem => {
                otherFile.push({
                  url: defaultImg,
                  status: "fail",
                  name: errItem.name,
                  raw: {
                    name: errItem.name,
                    tip: errItem.msg
                  }
                });
              });
            }
          } else {
            otherFile.push(fItem);
          }
        });
      }

      changeFileArr.value = filelist;
      uploadVedioMulitData.value = otherFile;
    } else {
      //单个视频上传
      playShow.value = true;

      defaultVedio.value = {};
      if (filelist.length == 1) {
        changeFileArr.value = filelist;
        console.log(filelist)
        if (filelist[0].status == "success") {
          defaultVedio.value = filelist[0].response;
         
        }
    
      } else {
        changeFileArr.value = [filelist[1]];
      }
  
    }
  }
};

const videoElement = ref(null);
const playShow = ref(true); //是否开始播放
const playVedioFun = (type, vindex, vedioItem) => {
  if (type == "mulit") {
    //多个视频
    console.log(vedioItem);
    console.log(inputRefMap.value);
    vedioItem.isPlay = true;
    inputRefMap.value[`videoRef_${vindex}`].play();
    return;
  }
  //单个视频
  playShow.value = false;
  videoElement.value.play();
};

const onVideoEnded = (type, vindex, vedioItem) => {
  if (type == "mulit") {
    //多个视频
    inputRefMap.value[`videoRef_${vindex}`].pause();
    inputRefMap.value[`videoRef_${vindex}`].currentTime = 0;
    vedioItem.isPlay = false;
    return;
  }
  //单视频
  videoElement.value.pause();
  videoElement.value.currentTime = 0;
  playShow.value = true;
};

const emit = defineEmits<{
  delVedioFun: any;
}>();
const delVedio = (type, vindex, vedioItem) => {
  if (type == "mulit") {
    //多个删除
    emit("delVedioFun", { type, rows: vedioItem });
    return;
  }
  // 单个删除
  if (fileObj.value.response) {
    emit("delVedioFun", { rows: fileObj.value.response });
  } else {
    delChangeFile(fileObj.value);
  }
     if(props.uploadClass=="picUpload"){
        //上传之后不显示上传控件
        haveOneUrl.value=true;
      }
};

//删除change数据
const delChangeFile = rows => {
  changeFileArr.value = [];
};

const delChangeFileMulit = rows => {
  // uploadSuccessData.value

  let uObj = {};
  changeFileArr.value.map((uItem, rIndex) => {
    if (uItem.response) {
      uObj[uItem.response.id] = uItem;
    } else {
      uObj[rIndex + 1] = uItem;
    }
  });
  changeFileArr.value = Object.values(uObj);

  let indexFilter = changeFileArr.value.findIndex(fitem => fitem.response?.id == rows.id);

  if (indexFilter > -1) {
    changeFileArr.value.splice(indexFilter, 1);
  }


  

  let rObj={};
  uploadVedioMulitData.value.map((rItem,rIndex)=>{
    if(rItem.response){
      rObj[rItem.response.id]=rItem;
    }else{
        rObj[rIndex+1]=rItem;
    }
  })
   uploadVedioMulitData.value= Object.values(rObj);
  let repeatedIndx=uploadVedioMulitData.value.findIndex(ritem => ritem.response?.id == rows.id);
    
    if (repeatedIndx > -1) {
    uploadVedioMulitData.value.splice(repeatedIndx, 1);
   
  }


 
};



const getErrUploadData = () => {
  let errDataArr = [];
  uploadVedioMulitData.value.map((v, vindex) => {
    if (v.status!= "success") {
      errDataArr.push({ ...v,url:defaultImg });
    }
  });
  return errDataArr;
};

defineExpose({
  baseUploadRef:computed(()=>uploadFileRef.value.refName),
  getErrUploadData,
  delChangeFileMulit,
  delChangeFile //清空change数据
});
onMounted(() => {
//   console.log(uploadFileRef.value)
// console.log(uploadFileRef.value?.readMe())
});
</script>
<style lang="scss" scoped>
@import url("./index.scss");
</style>
